package controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zxf.pojo.Users;
import com.zxf.service.UserService;

@RequestMapping("/user")  
@Controller
public class UserController {

	@Autowired 
	private UserService userService;
	
	
	// 用户表
	@RequestMapping(value="/save")  
    public @ResponseBody Map<String,Object> saveOrUpdate(HttpServletRequest request,     
            HttpServletResponse response){  
        Map<String,Object> responseMap = new HashMap<String,Object>();  
  
  Users user = new Users();  
                String newId = "80";  
                user.setUserid(newId);  
                user.setUsername("zxf");  
                user.setPassword("zxf");  
                Map<String,Object> param = new HashMap<String,Object>();  
                param.put("user_id", newId);  
                userService.insertUser(user, param);  
                responseMap.put("method", "Create");  
                responseMap.put("success", "true");  
                responseMap.put("info", "新增成功！"); 
                return responseMap; 
            }  
            
	// 用户列表
	@RequestMapping("/userlist")
		public @ResponseBody JSONObject userlist(String page, String limit , String start,HttpServletRequest request, HttpServletResponse response) {
			 JSONObject obj = new JSONObject();
			// StringBuffer toJson=new StringBuffer();//用来放json数据 
			 JSONArray js = new JSONArray();
			 //页码
			int pageno = Integer.parseInt(page);
			//每页数量
			int pageSize2 = Integer.parseInt(limit);
			 //int start2 = (Integer.parseInt(pageno)-1)*Integer.parseInt(pageSize);
			 int start2 = (pageno-1)*pageSize2;
			//Map<String, Object> userlist2 =  (Map<String, Object>) userService.getUserList3(start2,Integer.parseInt(start));
		List userlist2 =  userService.getUserList3(start2,pageSize2);
		int totle = userService.getusertotle();
		//System.out.println(pageno==1?pageno:(pageno-1));
		obj.put("data", js.fromObject(userlist2));
		 obj.put("total", totle); //统计数量，这里写死10条
		 obj.put("success", true);
			
				// response.setHeader("Cache-Control", "no-cache");
				// response.setContentType("text/json;charset=utf-8"); 
				//response.getWriter().write(obj.toString());
				// TODO Auto-generated catch block
			//json格式化后输出
			 System.out.println(obj.toString());
				return obj;
			
		}

	// 用户登录
		@RequestMapping("/userlogin")
			public @ResponseBody JSONObject userlogin(Users users,HttpServletRequest request, HttpServletResponse response) {
				 JSONObject obj = new JSONObject();
				 HttpSession session = request.getSession(); 
				// StringBuffer toJson=new StringBuffer();//用来放json数据 
				 //shiro验证
				/* Subject subject = SecurityUtils.getSubject();
		            // 已登陆则 跳到首页
				 
				 UsernamePasswordToken token = new UsernamePasswordToken(  
			                users.getUserid().toString(), users.getPassword());  
			        token.setRememberMe(true);
			        subject.login(token);
			        
			        
		            if (subject.isAuthenticated()) {
		            	session.setAttribute("userinfo", users); 
		                //return "redirect:/";
		            }*/
				 JSONArray js = new JSONArray();
				 Users users2 = new Users();
				//得到生成的验证码  
			     String strCode = (String) session.getAttribute("randomCode");  
			     System.out.println("UserAction>randomCode:"+strCode);  
				    //定义一个msg变量，可用于存放错误信息，然后传到前台  
				    //用于告诉前台时候登录成功  
				 boolean successe = false;
				 if(!users.getCheckCode().toLowerCase().equals(strCode.toLowerCase())){
					 obj.put("success", false);
					 obj.put("message", "验证码错误！");
					 return obj;
					 
				 }
				 
				 users2 = userService.selectusers(users);
				 
				
				 
				if(null != users2){
					obj.put("users", users2); 
					obj.put("success", true);
					session.setAttribute("userInfo", users2.getUsername());
					
				}
				else{
					obj.put("success", false);
					 obj.put("message", "用户名或者密码错误！");
					
				}
			
				
					// response.setHeader("Cache-Control", "no-cache");
					// response.setContentType("text/json;charset=utf-8"); 
					//response.getWriter().write(obj.toString());
					// TODO Auto-generated catch block
				//json格式化后输出
				 System.out.println(obj.toString());
					return obj;
				
			}
		
		// 用户登录
				@RequestMapping("/buserlogin")
					public @ResponseBody JSONObject buserlogin(String username,String password,HttpServletRequest request, HttpServletResponse response) {
						 JSONObject obj = new JSONObject();
						 HttpSession session = request.getSession(); 
						// StringBuffer toJson=new StringBuffer();//用来放json数据 
						String username2 =  request.getParameter("username");//就能获取到value 
						 JSONArray js = new JSONArray();
						 Users users = new Users();
						 Users users2 = new Users();
						 users.setUsername(username);
						 users.setPassword(password);
						//得到生成的验证码  
					     String strCode = (String) session.getAttribute("randomCode");  
					     System.out.println("UserAction>randomCode:"+strCode);  
						    //定义一个msg变量，可用于存放错误信息，然后传到前台  
						    //用于告诉前台时候登录成功  
						 boolean successe = false;
						
						 
						 users2 = userService.selectusers(users);
						 
						
						 
						if(null != users2){
							obj.put("users", users2); 
							obj.put("success", true);
							
						}
						else{
							obj.put("success", false);
							 obj.put("message", "用户名或者密码错误！");
							
						}
					
						
							// response.setHeader("Cache-Control", "no-cache");
							// response.setContentType("text/json;charset=utf-8"); 
							//response.getWriter().write(obj.toString());
							// TODO Auto-generated catch block
						//json格式化后输出
						 System.out.println(obj.toString());
							return obj;
						
					}
	
}
